//app.js
var userModel = require('models/user.js')
var klassModel = require('models/klass.js')
var request = require('operation/operation.js')
var notificationCenter = require('/utils/notification.js');

App({
  notificationCenter: null,
  
  globalData: {
    userInfo: null,
    wxUserInfo: null,
    param: {},  // 用于保存页面参数传值
    currentPage: ''  // 用于保存创建通知界面返回的路径，仅 通知列表、和我的界面会进行设置
  },

  onLaunch: function (options) {
    this.globalData.userInfo = userModel.getCurrentUser()
    this.globalData.wxUserInfo = userModel.getCurrentWxUser()
    this.globalData.param = {}

    this.notificationCenter = notificationCenter.center();
  },

  onShow: function (options) {
    if (this.globalData.userInfo) {
      var that = this
      wx.checkSession({
        success: function (res) {
          //session 未过期，并且在本生命周期一直有效
        },
        fail: function () {
          //登录态过期
          // that.getUserInfo(null, true)
        }
      })
    }

    if (options.path.indexOf('noticeDetail/noticeDetail') >= 0 && (options.scene == 1007 || options.scene == 1008 || options.scene == 1044)) {
      // 通过群/个人分享卡片进来
      this.globalData.param.appOptions = options
    } else {
      if (!userModel.getCurrentUser() || 0 == klassModel.getCurrentAllClass().length) {// 本地没有用户信息或者没有创建\加入一个班级，进入介绍界面
        wx.reLaunch({
          url: '../pages/introduce/introduce',
        })
      }
    }
    
  },

  /**
   * 获取用户微信信息及在系统的用户信息
   * param function(wxUserInfo,userInfo,message)
   */
  getUserInfo: function (wxUserInfo, cb, forceLogin=false) {
    var that = this
  
    this.globalData.userInfo = userModel.getCurrentUser()
    this.globalData.wxUserInfo = userModel.getCurrentWxUser()
    if (this.globalData.userInfo && this.globalData.wxUserInfo && !forceLogin) {
      typeof cb == "function" && cb(that.globalData.wxUserInfo, this.globalData.userInfo, '')
    } else {
      //调用登录接口
      wx.login({
        success: function (res) {
          var code = res.code
          // console.log('code')
          // console.log(code)
          // console.log(wxUserInfo)
          wxUserInfo.userInfo.code = code
          that.logon(wxUserInfo, cb)                            
        },
        fail: function (res) {
          console.log(res)
          cb(null, null, '微信获取用户信息失败')
        }
      })
    }
  },

  // 更新用户信息
  updateUserInfo: function (cb) {
    var that = this
    request.getRequest('/user-info', {},true)
      .then(res => {
        if (request.SUCCESSED == res.data.status) {
          res.data.user.accessToken = that.globalData.userInfo.accessToken  // 更新用户信息时，服务器没有返回accessToken信息，需要将原来保存的重新设置给返回数据
          that.globalData.userInfo = res.data.user
          that.globalData.userInfo.asKlassCreator = res.data.asKlassCreator
          that.globalData.userInfo.asTeacher = res.data.asTeacher
          that.globalData.userInfo.asRelation = res.data.asRelation
          that.globalData.userInfo.klassRoles = res.data.klassRoles
          userModel.setCurrentUser(that.globalData.userInfo)
          klassModel.setCurrentAllClass(res.data.klasses)

          typeof cb == "function" && cb(that.globalData.userInfo)
        } else {
          typeof cb == "function" && cb(null)
        }

      }).catch(e => {
        console.log(e)
        typeof cb == "function" && cb(null)
      })
  },

  // 登录请求
  logon: function (wxUserInfo, cb) {
    var that = this, params = { 'nickname': wxUserInfo.userInfo.nickName, 'wxCode': wxUserInfo.userInfo.code, 'avatar': wxUserInfo.userInfo.avatarUrl}
    if (wxUserInfo.encryptedData) {      
      params.encryptedData = wxUserInfo.encryptedData
      params.iv = wxUserInfo.iv
    }
  
    request.postRequest('/wx-login', params, false)
      .then(res => {
        if (request.SUCCESSED == res.data.status) {
          that.globalData.wxUserInfo = wxUserInfo
          that.globalData.userInfo = res.data.user
          that.globalData.userInfo.asKlassCreator = res.data.asKlassCreator
          that.globalData.userInfo.asTeacher = res.data.asTeacher
          that.globalData.userInfo.asRelation = res.data.asRelation
          that.globalData.userInfo.klassRoles = res.data.klassRoles
          userModel.setCurrentUser(that.globalData.userInfo)
          userModel.setCurrentWxUser(that.globalData.wxUserInfo)
          klassModel.setCurrentAllClass(res.data.klasses)
          // if (res.data.klasses && 1 == res.data.klasses.length) { // 只有一个班级时，默认选择第一个班级
          //   klassModel.setCurrentClass(res.data.klasses[0])
          // }
          
          typeof cb == "function" && cb(that.globalData.wxUserInfo, that.globalData.userInfo, '')
        } else {
          cb(null, null, '登录失败')
        }
      }).catch(e => {
        cb(null, null, '登录失败')
      })
  },

  /**
   * 收集用户formId，用于服务器推送通知使用
   */
  createFormId:function(formId) {
    request.postRequest('/new-form-id', {'formId':formId}, true,false)
      .then(res => {
        if (request.SUCCESSED == res.data.status) {
         
        }
      }).catch(e => {
        
      })
  },

  /**
   * 绑定通知与班级的关系
   */

  bindNoticeToClass: function (shareTickets,noticeSid,kcalssSid,callbackFn) {
    // wx.getShareInfo({
      // shareTicket: shareTickets[0],
      // success: function(res) {
          // request.postRequest('/notice-klasses', { 'noticeSid': noticeSid, 'klassSid': kcalssSid, 'encryptedData': res.encryptedData,'iv':res.iv}, true)
    request.postRequest('/notice-klasses', { 'noticeSid': noticeSid, 'klassSid': kcalssSid}, true)
            .then(result => {
              if (request.SUCCESSED == result.data.status) {
                callbackFn(result)
              } else {
                if (result.data.status != -4) {
                  wx.showModal({
                    title: '提示',
                    content: result.data.msg,
                    showCancel: false,
                  })
                }               
              }

            }).catch(e => {
              console.log(e)
            })
      // },
      // fail: function(res) {},
      // complete: function(res) {},
    // })
  },

  /**
   * 自动返回第一个界面
   */
  autoBack: function (msg,delta = 0) {
    wx.showToast({
      title: msg,
      icon: 'success',
    })

    if (delta == 0) {
      delta = getCurrentPages().length - 1
    }

    setTimeout(function () {
      wx.navigateBack({
        delta: delta
      })
    }
      , 1500)
  }

})